package com.demon.androidbasic.action

import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import com.demon.androidbasic.base.BaseBindActivity

/**
 * author : Android 轮子哥
 * github : https://github.com/getActivity/AndroidProject
 * time   : 2020/03/08
 * desc   : Activity 相关意图
 */
interface ActivityAction {
    /**
     * 获取 Context
     */
    val myContext: Context

    /**
     * 获取 Activity
     */
    val activity: BaseBindActivity<*>?
        get() {
            var context: Context? = myContext
            do {
                context = when (context) {
                    is BaseBindActivity<*> -> {
                        return context
                    }
                    is ContextWrapper -> {
                        context.baseContext
                    }
                    else -> {
                        return null
                    }
                }
            } while (context != null)
            return null
        }

    /**
     * 启动一个 Activity（简化版）
     */
    fun startActivity(clazz: Class<out Activity?>) {
        startActivity(Intent(myContext, clazz))
    }

    /**
     * 启动一个 Activity
     */
    fun startActivity(intent: Intent) {
        if (myContext !is Activity) {
            // 如果当前的上下文不是 Activity，调用 startActivity 必须加入新任务栈的标记
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }
        myContext.startActivity(intent)
    }
}